import { ClockInGetError, ClockInUpdateError } from '../constant/err.type.ts'
import { ClockInCreat } from '../interface/params.interface.ts'
import type { Context } from 'koa'
import { sendMail } from '../config/nodemailer.ts'
import { FontFamily, TimeFontFamily } from '../utils/Css.ts'
import { getTimorHolidayInfo } from '../service/phone.service.ts'
import moment from 'moment'

let allow: string = '0'
let timer: NodeJS.Timeout | null = null

class CheckinController {
  // 获取打卡允许状态
  async getClockinAllow(ctx: Context) {
    try {
      const data: ClockInCreat = {
        allow,
      }
      ctx.echo({ data })
    } catch (error) {
      ClockInGetError.error = error
      return ctx.app.emit('error', ClockInGetError, ctx)
    }
  }

  // 更新打卡允许状态
  async updateClockinAllow(ctx: Context) {
    try {
      const date = moment().format('YYYY-MM-DD')
      const res = await getTimorHolidayInfo(date)
      const { type, code } = res
      if (code === 0) {
        if (type.type === 0 || type.type === 3) {
          const { allow: allowNum, allowEmailNotice } = ctx.request.body
          if (allowNum === '1') {
            if (timer) clearTimeout(timer)
            // 随机延迟
            const randomSeconds = Math.ceil(Math.random() * 5)
            timer = setTimeout(
              () => {
                allow = allowNum
              },
              1000 * 60 * randomSeconds,
            )
          } else {
            // 立即转变成不允许打卡
            if (timer) clearTimeout(timer)
            allow = allowNum
            if (allowEmailNotice === '1') {
              const html = `<p style=${FontFamily}></p>于 <span style=${TimeFontFamily}>${moment().format(
                'YYYY-MM-DD HH:mm',
              )}</span> 打卡成功`
              const options = {
                subject: '【打卡】',
                html,
              }
              await sendMail(options)
            }
          }
          ctx.echo({ msg: '更新成功' })
        } else {
          ctx.echo({ code: 201 })
        }
      } else {
        ctx.echo({ code: 201 })
      }
    } catch (error) {
      ClockInUpdateError.error = error
      return ctx.app.emit('error', ClockInUpdateError, ctx)
    }
  }
}

const checkinController = new CheckinController()
export const { getClockinAllow, updateClockinAllow } = checkinController
export default checkinController
